<script lang="ts" setup>
import type {PhotoInfo} from "@/types/animals";
import {onLoad} from "@dcloudio/uni-app";
import {onMounted, ref} from "vue";
import type {Result} from "@/types/Result";
import {useUserStore} from "@/stores/user";

onLoad((options: any) => {
  filePath.value = options.originUrl
  originUrl.value = options.originUrl
  // 请求
  startUpload(filePath.value)
})
const animalInfo = ref<PhotoInfo>()
const filePath = ref()
const error = ref(false) // 识别出错时
const originUrl = ref() // 原始图片地址
const isExpand = ref(true) // 展开
const goBack = () => {
  uni.navigateBack()
}


// 图片上传
const progress = ref(0)
const startUpload = async (path: string) => {
  progress.value = 0
  animalInfo.value = {} as PhotoInfo
  loading.value = true
  error.value = false
  uni.uploadFile({
    url: '/photo',
    name: 'file',
    filePath: path,
    timeout: 20000,
    success(res) {
      // 判断是否上传成功
      loading.value = false
      const resultData = JSON.parse(res.data) as Result<PhotoInfo>

      if (resultData.code !== '1') {
        error.value = true
        return uni.showToast({title: '图片识别错误，请稍后重试', duration: 3000, icon: 'none'})
      } else if (resultData.data.result === null || resultData.data.result.length === 0) {
        error.value = true
        return uni.showToast({title: '未识别到动物，请稍后重试', duration: 3000, icon: 'none'})
      } else {
        if (resultData.data?.result[0].name === '非动物') {
          error.value = true
          return uni.showToast({title: '未识别到动物，请稍后重试', duration: 3000, icon: 'none'})
        }
      }
      animalInfo.value = resultData.data
    },
    fail(err) {
      loading.value = false
      error.value = true
      console.log(err)
      uni.showToast({
        title: '图片识别错误',
        icon: 'error',
      })
    }
  })
}
// 选择图片
const goPhoto = () => {
  uni.chooseImage({
    mediaType: ['image'],
    sourceType: ['album', 'camera'],
    count: 1, //默认9
    sizeType: ['compressed'],
    success: (res: any) => { // It's hard to find a type here
      originUrl.value = res.tempFiles[0].path
      if (res.tempFiles[0].size > 4 * 1024 * 1024) {
        return uni.showToast({title: '图片大小不能超过4MB', icon: 'none'})
      }
      startUpload(originUrl.value)
    }
  })
}
// 骨架
const loading = ref(false)
const skeleton = [
  {
    type: 'flex',
    children: [{
      type: 'custom',
      style: 'width:98px;height:60px;'
    }, {
      type: 'custom',
      style: 'width:98px;height:60px;'
    }, {
      type: 'custom',
      style: 'width:98px;height:60px;'
    }]
  },
  30,
  {
    type: 'line',
    num: 2,
    style: ['height:50rpx;width:100rpx;', "width:150rpx;"]
  },
  40,
  {
    type: 'flex',
    num: 1,
    children: [{
      type: 'line',
      num: 4,
      style: ["width:360rpx;", 'width:360rpx;', 'width:360rpx;', 'width:360rpx;']
    }, {
      type: 'custom',
      num: 1,
      style: 'width:120px;height:120px;marginLeft: 30px;'
    },]
  },
  20, {
    type: 'line',
    num: 1,
    style: ['width:150rpx']
  }
]
onMounted(() => {
  // infoPopup.value.open()
})
const change = () => {

}

// 当前选中动物
const activeIndex = ref(0)
const unfold = ref(false)
// 切换动物
const handleChange = (index: number) => {
  activeIndex.value = index
  unfold.value = false
}
const handleUnfold = () => {
  unfold.value = !unfold.value
}

const goBaiKe = () => {
  uni.navigateTo({
    url: '/subPkg/web/web?url=' + 'https://baike.baidu.com/item/' + animalInfo.value?.result[activeIndex.value].name + '&&title=' + animalInfo.value?.result[activeIndex.value].name
  })
}

// 点击搜索出的图片预览
const handlePreview = () => {
  let url
  if (animalInfo.value?.result[activeIndex.value].baike_info.image_url) {
    url = animalInfo.value?.result[activeIndex.value].baike_info.image_url
  } else {
    return uni.showToast({title: '暂无图片', icon: 'none'})
  }
  uni.previewImage({
    urls: [url]
  })
}

// 裁剪
const cropper = ref()
// 关闭裁剪
const onCancel = () => {
}
const test = ref()
// 裁剪确认
const onConfirm = (res: any) => {
  // 设置url的值，显示控件

  const file = res.tempFilePath
  startUpload(file)
  delay.value = false
}
const delay = ref(false)
const handleCutConfirm = () => {

  // #ifndef H5
  if (!isMove.value) {
    return
  }
  // #endif
  if (delay.value) {
    return
  }
  delay.value = true
  loading.value = true
  isExpand.value = true
  try {
    cropper.value.onConfirm()
  } catch (e) {
    console.log(e)
  }
}

const isMove = ref(false)
const initMove = () => {
  isMove.value = true
}
</script>

<template>
  <view class="photo-container padding-top-sm">
    <view class="photo-picture" @touchmove="initMove">
      <t-cropper
          ref="cropper"
          :imageUrl="originUrl"
          :isRotateBtn="false"
          :maxRatio="1"
          :minRatio="1"
          :radius="0"
          :scaleRatio="0.7"
          mode="free"
          @cancel="onCancel"
          @confirm="onConfirm"
      ></t-cropper>
    </view>

    <view :z-index="10">
      <view class="cuIcon-roundrightfill  round"
            style="position: absolute;left: 4%;top: 4%;font-size: 36px;transform: rotate(180deg);color: #f1f1f1;opacity: 0.7"
            @click="goBack"></view>
      <ww-bottom-drawerapp :dragHandleHeight="22" :is-expand="isExpand" :proportionShow='0.35' proportionMiniShow="0.2">
        <slot>

          <!--       骨架skeleton   -->
          <view v-if="loading" class="drawer-skeletons padding-lg">
            <view class="flex text-lg text-black align-center justify-start" style="gap: 10px">
              <view>识别图片中</view>
              <uv-loading-icon :color="'#39c5bb'" mode="circle"></uv-loading-icon>
            </view>
            <uv-divider></uv-divider>
            <uv-skeletons :loading="true" :skeleton="skeleton"></uv-skeletons>
          </view>
          <!--      内容区    -->

          <scroll-view v-else :scroll-y="true" class="drawer">
            <view v-if="error" class="flex justify-center align-center" style="width: 100%;height: 50vh">
              <uv-empty icon-size="125"></uv-empty>
            </view>
            <view v-else class="flex justify-start flex-column text-black padding-lg "
                  style="width: 100%;height: 100%;row-gap: 5px">
              <view style="height: 35px">按照图片
                <text class="text-awGreen">相似度</text>
                推荐
                <uv-divider></uv-divider>
              </view>
              <view class="flex justify-around flex-wrap" style="width: 100%;gap: 4%;height: 30%">
                <!--    选项-->
                <view v-for="(item,index) in animalInfo?.result" :class="[index===activeIndex?'active':'']"
                      class="flex justify-center align-center"
                      style="width:30%;height:60px;overflow: hidden;border-radius: 10px;position: relative;box-sizing: border-box"
                      @click="handleChange(index)">
                  <view style="position: absolute;left: 0;top: 0;width: 100%;height: 100%;z-index: 1">
                    <uv-image :src="item.baike_info.image_url" mode="widthFix"
                              width="100%">
                    </uv-image>
                  </view>
                  <view class="flex justify-center align-center flex-column text-bold text-white"
                        style="background-color: rgba(0,0,0,0.5);z-index: 10;width: 100%;height: 100%;row-gap: 5px">
                    {{ item.name }}
                    <view v-show="index===activeIndex"
                          style="width: 1rem;height: 2px;border-radius: 1px;background: #FFFFFF"></view>
                  </view>
                </view>
                <!--      姓名        -->
                <view class="flex justify-start flex-column  margin-tb-lg" style="width: 100%;row-gap: 10px">
                  <view class="text-bold text-black text-xl ">{{ animalInfo?.result[activeIndex].name }}
                  </view>
                  <view class="text-gray">相似度
                    <text v-show="animalInfo?.result[activeIndex]?.score" :class="[animalInfo?.result[activeIndex].score>0.3
                                  ?animalInfo?.result[activeIndex].score>0.6
                                  ?animalInfo?.result[activeIndex].score>0.8
                                  ?'similarity80'
                                  :'similarity60'
                                  :'similarity60'
                                  :'similarity30']">{{ (animalInfo?.result[activeIndex].score * 100).toFixed(2) }}%
                    </text>
                  </view>
                </view>
                <!--      简介        -->
                <view class="flex justify-between" style="width: 100%;column-gap: 20px">
                  <text :selectable="true" :user-select="true" style="line-height: 1.5rem">
                    <text class="cu-tag  text-white radius margin-right-sm text-bold"
                          style="font-size: 10px;width: 1.6rem;height:1.2rem;margin-right: .5rem;background: #0055ff">百科
                    </text>
                    {{
                      animalInfo?.result[activeIndex].baike_info.description?.length > 130
                          ? animalInfo?.result[activeIndex].baike_info.description.substring(0, 103)
                          : animalInfo?.result[activeIndex].baike_info.description
                    }}
                    <text v-show="animalInfo?.result[activeIndex].baike_info.description?.length  > 130&&!unfold"
                          class="text-awGreen" @click="handleUnfold">{{ '展开' }}
                    </text>
                    <text v-if="!animalInfo?.result[activeIndex].baike_info.description" class="text-gray">
                      暂无详细资料，可点击下方百科链接进行查询
                    </text>
                  </text>
                  <view style="height: 120px;">
                    <uv-image :src="animalInfo?.result[activeIndex].baike_info.image_url" height="120px"
                              mode="aspectFill" radius="10%" width="120px" @click="handlePreview">
                      <template v-slot:error>
                        <view class="text-lg">图片暂无</view>
                      </template>
                    </uv-image>
                  </view>
                </view>
                <view style="width: 100%">
                  <text v-show="unfold" :selectable="true" :user-select="true" style="line-height: 1.5rem;">
                    {{ animalInfo?.result[activeIndex].baike_info.description?.substring(103) }}
                  </text>
                  <text v-show="animalInfo?.result[activeIndex].baike_info.description?.length  > 130&&unfold"
                        class="text-awGreen margin-left-sm" @click="handleUnfold">收起
                  </text>
                </view>

                <view class="flex justify-start margin-top-sm" style="width: 100%">
                  <view class="flex justify-start align-center  padding-bottom-lg text-blue"
                        style="font-size: 14px ;text-decoration-line: underline" @tap="goBaiKe">
                    百度百科链接
                    <view>
                      <uv-icon color="#000" name="share-square" size="14"></uv-icon>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </scroll-view>
        </slot>
      </ww-bottom-drawerapp>
      <view class="bottom-button bg-gray flex justify-around align-center padding-tb-lg">
        <view class="cu-btn bg-white  flex" style="border-radius: 8px;gap: 5px;font-size: 12px" @click="goPhoto">
          <text class="cuIcon-camera text-bold text-black" style="font-size: 18px"></text>
          重新选择
        </view>
        <view class="cu-btn bg-white  flex " style="border-radius: 10px;gap: 5px;font-size: 12px"
              @click.stop="handleCutConfirm">
          <text class="cuIcon-cut text-bold text-black" style="font-size: 18px"></text>
          确认裁剪
        </view>
      </view>
    </view>
  </view>
</template>


<style lang="scss" scoped>
.photo-container {
  background: #000000;
  color: #FFFFFF;
  width: 100%;
  height: 100vh;
  position: relative;
}

.photo-picture {
  width: 100%;
  height: 50vh;
}

.drawer {
  min-height: 60vh;
  max-height: 80vh;
  margin-bottom: 55px;
  z-index: 10;
}

.drawer-skeletons {
  min-height: 60vh;
}

.active {
  border: #39c5bb solid 3px;
}

.similarity30 {
  color: #f56c6c;
}

.similarity60 {
  color: #f9ae3d;
}

.similarity80 {
  color: #3ebed3;
}

.bottom-button {
  z-index: 9999;
  width: 100%;
  height: 55px;
  position: absolute;
  bottom: 0;
  left: 0
}
</style>
